package de.gwtprime.client.widgets.trading;


import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.util.GWTUtils;
import de.gwtprime.client.widgets.helper.InfoPopup;
import de.gwtprime.client.widgets.trading.popup.OrderCreationConfirmationPopup;
import de.gwtprime.shared.requestFactory.OrderProxy;
import de.gwtprime.shared.requestFactory.OrderProxy.OrderType;
import de.gwtprime.shared.requestFactory.request.OrderRequest;
import de.gwtprime.shared.util.AppUtilsShared;

public class TradeWidget extends Composite{

	private static TradeWidgetUiBinder uiBinder = GWT
			.create(TradeWidgetUiBinder.class);

	interface TradeWidgetUiBinder extends UiBinder<Widget, TradeWidget> {
	}

	public static Double currentPrice = 10d;
	@UiField  RadioButton radioBtnBuy; // buy button
	@UiField  RadioButton radioBtnSell; // sell button

	@UiField TextBox amountInput;

	@UiField ListBox lb;

	@UiField TextBox price;

	@UiField Button button;

	@UiField Label completePriceLabel;

	ClientFactory clientFactory;
	
	public TradeWidget(final ClientFactory clientFactory) {
		initWidget(uiBinder.createAndBindUi(this));

		this.clientFactory = clientFactory;
		
		radioBtnBuy.setText(GWTUtils.I18n.buyBtn());
		radioBtnBuy.setValue(true);

		// If the buy radio button is selected -> Label the process button as "buy"
		radioBtnBuy.addValueChangeHandler(new ValueChangeHandler<Boolean>() {

			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				button.setText(GWTUtils.I18n.buyBtn());

			}
		});

		// If the sell radio button is selected -> Label the process button as "sell"
		radioBtnSell.addValueChangeHandler(new ValueChangeHandler<Boolean>() {

			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				button.setText(GWTUtils.I18n.sellBtn());

			}
		});

		radioBtnSell.setText(GWTUtils.I18n.sellBtn());

		amountInput.getElement().setPropertyString("placeholder", "1");


		amountInput.addKeyUpHandler(new KeyUpHandler() {

			@Override
			public void onKeyUp(KeyUpEvent event) {
				updatePriceOnUI();					
			}
		});
		price.getElement().setPropertyString("placeholder", currentPrice.toString());

		lb.addItem("market");
		lb.addItem("limit");
		
		if(!AppUtilsShared.useSimpleTrading)
			price.setEnabled(false);
		lb.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				int index = lb.getSelectedIndex();

				price.setValue("");
				price.getElement().setPropertyString("placeholder", currentPrice.toString());

				if(index==0){
					//price.setValue(currentPrice.toString());
					price.setEnabled(false);
				}

				if(index==1){
					price.setEnabled(true);
					//price.setValue("");
				}

				updatePriceOnUI();
			}

		});
		
		if(AppUtilsShared.useSimpleTrading)
			lb.setVisible(false);


		completePriceLabel.setText(currentPrice.toString());

		amountInput.setWidth("50px");

		price.setWidth("50px");
		button.setText(GWTUtils.I18n.buyBtn());

		price.addKeyUpHandler(new KeyUpHandler() {

			@Override
			public void onKeyUp(KeyUpEvent event) {
				updatePriceOnUI();					
			}
		});


		button.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				if(clientFactory.getUser()==null){
					
					new InfoPopup(GWTUtils.I18n.notLoggedIn()).center();
					return;
				}
				
				Double count = 0d;
				Double price1 = currentPrice;      
				try{

					count = Double.parseDouble(amountInput.getText());
					price1 = Double.parseDouble(price.getText());

				}catch(Exception e){
					new InfoPopup(GWTUtils.I18n.orderInvalidInput()).center();
					return;
				}
				
				if(!(count>0)){
					
					new InfoPopup(GWTUtils.I18n.numberCoinsNeedsToBeBiggerThanZero()).center();
					return;
				}
				
				OrderRequest request = clientFactory.getRequestFactory().orderRequest();
				final OrderProxy order = request.create(OrderProxy.class);
				
				
				if(radioBtnBuy.getValue()){ // BUY ORDER
					order.setType(OrderType.BUY);
					order.setBuyer(clientFactory.getUser());
				}else if(radioBtnSell.getValue()){ // SELL ORDER
					
					// If user wants to create a sell order, but does not have enough
					// coins -> abort and show him a message
					if(count>clientFactory.getUser().getBalanceBitcoin()){
						new InfoPopup(GWTUtils.I18n.notEnoughCoins()).center();
						return;
					}
					
					order.setType(OrderType.SELL);
					order.setSeller(clientFactory.getUser());
				}
				order.setAmount(count);
				order.setPrice(price1);
				order.setUser(clientFactory.getUser());
				
				new OrderCreationConfirmationPopup(clientFactory, order, request).center();

			}
		});

	}

	/**
	 * Try to parse the input values of the amount and price box
	 * and calculate the total price
	 * @param amount
	 * @param price
	 * @return
	 */
	public Double calculatePrice(String amount, String price){

		Double count;
		Double price1;
		try{

			count = Double.parseDouble(amount);

		}catch(Exception e){
			count = 0d;
		}

		try{

			if(price==null || "".equals(price)){
				price1=currentPrice;
			}else{
				price1 = Double.parseDouble(price);
			}

		}catch(Exception e){
			price1 = 0d;
		}

		return count*price1;
	}

	public void updatePriceOnUI(){
		completePriceLabel.setText(calculatePrice(amountInput.getValue(), price.getValue()).toString());
	}

	  public static class Contact {
		    final String address;
		     final Date birthday;
		    final String name;

		    public Contact(String name, Date birthday, String address) {
		      this.name = name;
		      this.birthday = birthday;
		      this.address = address;
		    }
		  }

}


